package com.zut.chat.controller;

import com.zut.chat.entity.SysUser;
import com.zut.chat.service.SysUserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/auth")
public class AuthController {
    
    @Autowired
    private SysUserService sysUserService;
    
    /**
     * 管理员登录
     */
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Map<String, String> loginData, 
                                  HttpServletRequest request) {
        String username = loginData.get("username");
        String password = loginData.get("password");
        
        if (username == null || username.trim().isEmpty() || 
            password == null || password.trim().isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "用户名和密码不能为空");
            return ResponseEntity.badRequest().body(errorResponse);
        }
        
        // 获取客户端IP
        String clientIp = getClientIp(request);
        
        // 验证登录
        SysUser sysUser = sysUserService.login(username, password, clientIp);
        
        if (sysUser != null) {
            // 登录成功，保存到session
            HttpSession session = request.getSession();
            session.setAttribute("adminUser", sysUser);
            session.setMaxInactiveInterval(8 * 60 * 60); // 8小时过期
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "登录成功");
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("id", sysUser.getId());
            userInfo.put("username", sysUser.getUsername());
            userInfo.put("realName", sysUser.getRealName() != null ? sysUser.getRealName() : sysUser.getUsername());
            result.put("user", userInfo);
            
            return ResponseEntity.ok(result);
        } else {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "用户名或密码错误");
            return ResponseEntity.ok(errorResponse);
        }
    }
    
    /**
     * 检查登录状态
     */
    @GetMapping("/check")
    public ResponseEntity<?> checkAuth(HttpSession session) {
        SysUser adminUser = (SysUser) session.getAttribute("adminUser");
        
        if (adminUser != null) {
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("id", adminUser.getId());
            userInfo.put("username", adminUser.getUsername());
            userInfo.put("realName", adminUser.getRealName() != null ? adminUser.getRealName() : adminUser.getUsername());
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("user", userInfo);
            return ResponseEntity.ok(response);
        } else {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "未登录");
            return ResponseEntity.ok(response);
        }
    }
    
    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public ResponseEntity<?> logout(HttpSession session) {
        session.invalidate();
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "退出成功");
        return ResponseEntity.ok(response);
    }
    
    /**
     * 获取客户端IP地址
     */
    private String getClientIp(HttpServletRequest request) {
        String clientIp = request.getHeader("X-Forwarded-For");
        if (clientIp == null || clientIp.isEmpty() || "unknown".equalsIgnoreCase(clientIp)) {
            clientIp = request.getHeader("X-Real-IP");
        }
        if (clientIp == null || clientIp.isEmpty() || "unknown".equalsIgnoreCase(clientIp)) {
            clientIp = request.getRemoteAddr();
        }
        // 如果是多个IP，取第一个
        if (clientIp != null && clientIp.contains(",")) {
            clientIp = clientIp.split(",")[0].trim();
        }
        return clientIp;
    }
} 